﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using ShenNius.Cms.API.Domain.Entity;
using ShenNius.Cms.API.Dtos.Input;
using ShenNius.Repository;
using ShenNius.Repository.Extensions;
using ShenNius.Sys.API.Controllers;
using ShenNius.Sys.API.Domain.Entity;
using ShenNius.Sys.API.Dtos.Common;
using ShenNius.Sys.API.Infrastructure;
using ShenNius.Sys.API.Infrastructure.Attributes;
using ShenNius.Sys.API.Infrastructure.Common;
using ShenNius.Sys.API.Infrastructure.Configs;
using SqlSugar;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

/*************************************
* 类名：ColumnController
* 作者：realyrare
* 邮箱：mahonggang8888@126.com
* 时间：2021/3/11 17:24:30
*┌───────────────────────────────────┐　    
*│　   版权所有：神牛软件　　　　	     │
*└───────────────────────────────────┘
**************************************/

namespace ShenNius.Cms.API.Controllers
{
    [Route("api/cms/[controller]/[action]")]
    public class ColumnController : ApiTenantBaseController<Column, DetailTenantQuery, DeletesTenantInput, KeyListTenantQuery, ColumnInput, ColumnModifyInput>
    {
        private readonly IBaseRepository<Column> _repository;
        private readonly IMapper _mapper;
        private readonly ISqlSugarClient _db;
        private readonly ICurrentUserContext _currentUserContext;

        public ColumnController(IBaseRepository<Column> repository, IMapper mapper, ISqlSugarClient ISqlSugarClient, ICurrentUserContext currentUserContext) : base(repository, mapper)
        {
            _repository = repository;
            _mapper = mapper;
            _db = ISqlSugarClient;
            _currentUserContext = currentUserContext;
        }

        [HttpGet]
        public override async Task<ApiResult> GetListPages([FromQuery] KeyListTenantQuery query)
        {
            var res = await _db.Queryable<Column>().Where(d => d.IsDeleted == false && d.TenantId == query.TenantId)
               .WhereIF(!string.IsNullOrEmpty(query.Key), c => c.Title.Contains(query.Key))
               .OrderBy(c => c.CreateTime, OrderByType.Desc)
               .ToPageAsync(query.Page, query.Limit);
            var tenants = await _db.Queryable<Tenant>().Where(d => d.IsDeleted == false).ToListAsync();
            foreach (var item in res.Items)
            {
                item.TenantName = tenants.Where(d => d.Id == item.TenantId).Select(d => d.Name).FirstOrDefault();
            }
            var result = new List<Column>();
            if (!string.IsNullOrEmpty(query.Key))
            {
                var menuModel = await _repository.GetModelAsync(m => m.Title.Contains(query.Key));
                WebHelper.ChildNode(res.Items, result, menuModel.ParentId);
            }
            else
            {
                WebHelper.ChildNode(res.Items, result, 0);
            }
            if (result?.Count > 0)
            {
                foreach (var item in result)
                {
                    var title = WebHelper.LevelName(item.Title, item.Layer);
                    item.ChangeTitle(title);
                }
                return new ApiResult(data: new { count = res.TotalItems, items = result });
            }
            else
            {
                return new ApiResult(data: new { count = res.TotalItems, items = res.Items });
            }
        }
        [HttpPost, Authority]
        public override async Task<ApiResult> Add([FromBody] ColumnInput columnInput)
        {
            var columnModel = await _repository.GetModelAsync(d => d.Title.Equals(columnInput.Title) && !d.IsDeleted);
            if (columnModel?.Id > 0)
            {
                return new ApiResult("已经存在类目名称了");
            }
            var column = _mapper.Map<Column>(columnInput);
            var columnId = await _repository.AddAsync(column);
            column.ChangeId(columnId);
            var result = await WebHelper.DealTreeData(columnInput.ParentId, columnId, async () =>
           await _repository.GetModelAsync(d => d.Id == columnInput.ParentId));

            column.ChangeParentList(result.Item1, result.Item2);
            var i = await _repository.UpdateAsync(column);
            return new ApiResult(i);
        }
        [HttpPut, Authority]
        public override async Task<ApiResult> Modify([FromBody] ColumnModifyInput input)
        {
            var columnModel = await _repository.GetModelAsync(d => d.Title.Equals(input.Title) && d.Id != input.Id && !d.IsDeleted);
            if (columnModel?.Id > 0)
            {
                return new ApiResult("已经存在类目名称了");
            }
            var result = await WebHelper.DealTreeData(input.ParentId, input.Id, async () =>
              await _repository.GetModelAsync(d => d.Id == input.ParentId));

            columnModel = _mapper.Map<Column>(input);
            columnModel.ChangeParentList(result.Item1, result.Item2);
            var i = await _repository.UpdateAsync(columnModel);
            return new ApiResult(i);
        }
        /// <summary>
        /// 所有父栏目
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetAllParentColumn()
        {
            var list = await _repository.GetListAsync(d => !d.IsDeleted && d.TenantId == _currentUserContext.TenantId);
            var data = new List<Column>();
            WebHelper.ChildNode(list, data, 0);
            if (data?.Count > 0)
            {
                foreach (var item in data)
                {
                    var title = WebHelper.LevelName(item.Title, item.Layer);
                    item.ChangeTitle(title);
                }
            }
            return new ApiResult(data);
        }
    }
}